import { lazyReportBatch } from "../report";

export const originalProto = XMLHttpRequest.prototype;
export const originalOpen = originalProto.open;
export const originalSend = originalProto.send;

//重写open和send方法
function overWriteOpenAndSend() {
  //改写原型上面的方法，所以this指向的是XMLHttpRequest实例
  originalProto.open = function newOpen(...args) {
    this.method = args[0];
    this.url = args[1];
    originalOpen.apply(this, args);
  };
  originalProto.send = function newSend(...args) {
    this.startTime = Date.now();
    const onLoad = () => {
      this.endTime = Date.now();
      this.duration = this.endTime - this.startTime;
      const { url, method, startTime, endTime, duration, status } = this;
      const reportData = {
        url,
        method: method.toUpperCase(),
        startTime,
        endTime,
        duration,
        status,
        type: "performance",
        success: status >= 200 && status < 300,
        subType: "xhr",
      };
      lazyReportBatch(reportData);
      this.removeEventListener("loadend", onLoad, true);
    };
    //loadend 事件是 XMLHttpRequest 事件，在请求完成（无论成功或失败）时触发。
    //true 捕获阶段触发（提高兼容性）
    this.addEventListener("loadend", onLoad, true);
    //apply() 方法会以给定的 this 值和作为数组（或类数组对象）提供的 args 调用该函数。
    originalSend.apply(this, args);
  };
}

export default function xhr() {
  overWriteOpenAndSend();
}
